package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    @Override
    public void remove(Long id) {
        /**
         * 根据category_id判断当前分类是否含有菜品
         * 若有，则不能删除该分类
         * 若没有，则判断是否关联了套餐
         * 关联，则不能删除该分类
         * 若没有，则正常删除
         * @param id
         */
        //如果关联菜品，则抛出一个业务异常
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //Dish里面的CategoryId属性
        //根据传入的分类id锁定其category_id，并记录等于这个category_id的菜品数量
        lqw.eq(Dish::getCategoryId,id);//注入条件
        int count = dishService.count(lqw);
        if(count > 0){
            //已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        //判断是否关联了套餐，如果已经关联，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(lqw2);
        if(count2 > 0){
            throw  new CustomException("当前分类下关联了套餐，不能删除");
        }
        //无关联，直接删除
        super.removeById(id);
        //如何将错误提示信息提示给页面：异常捕获器GlobalExceptionHandler

    }
}
